package com.myb.saas.ms.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.myb.common.util.DateUtil;
import com.myb.saas.agent.constant.CmdConstant;
import com.myb.saas.agent.vo.CmdInvoiceCallbackVo;
import com.myb.saas.agent.vo.MybCheckCallbackVo;
import com.myb.saas.agent.vo.MybPayCallbackVO;
import com.myb.saas.finance.service.StatementTransportDataService;
import com.myb.saas.order.model.Appoint;
import com.myb.saas.order.model.AppointExtra;
import com.myb.saas.pay.enums.LogisticsBizTypeEnum;
import com.myb.saas.pay.po.ExtContentPO;
import com.myb.saas.pay.po.PayMentOrderPO;
import com.myb.saas.transport.enums.TransportStatusEnum;
import com.myb.saas.transport.model.TransportOrderExt;
import com.myb.saas.transport.po.LogisticsSignPO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.myb.common.constant.Constant;
import com.myb.common.exception.ServiceException;
import com.myb.common.util.CollectionUtil;
import com.myb.common.util.EqualsUtil;
import com.myb.common.util.JsonUtil;
import com.myb.common.util.MapUtil;
import com.myb.common.util.ObjectUtil;
import com.myb.common.util.StringUtil;
import com.myb.saas.agent.constant.MybConstant;
import com.myb.saas.agent.service.logistics.LogisticsService;
import com.myb.saas.agent.service.logistics.MybService;
import com.myb.saas.base.service.SmsCodeService;
import com.myb.saas.driver.enums.AuditStatusEnum;
import com.myb.saas.driver.enums.ChannelTypeEnum;
import com.myb.saas.driver.model.Driver;
import com.myb.saas.driver.model.DriverAudit;
import com.myb.saas.driver.model.DriverBank;
import com.myb.saas.driver.model.DriverCar;
import com.myb.saas.driver.service.DriverAuditService;
import com.myb.saas.driver.service.DriverBankService;
import com.myb.saas.driver.service.DriverCarService;
import com.myb.saas.driver.service.DriverService;
import com.myb.saas.ms.enums.MsEnum;
import com.myb.saas.order.service.AppointExtraService;
import com.myb.saas.order.service.AppointService;
import com.myb.saas.pay.service.WxPayService;
import com.myb.saas.transport.model.TransportOrder;
import com.myb.saas.transport.model.TransportOrderBank;
import com.myb.saas.transport.service.TransportOrderBankService;
import com.myb.saas.transport.service.TransportOrderExtService;
import com.myb.saas.transport.service.TransportOrderService;

/**
 * Myb回调业务处理
 * @className MybBackExcuteService 
 * @author wangqinghua
 * @date 2023年3月21日 上午10:18:18
 */
@Service
public class MybBackExcuteService {
	private static final Logger LOGGER = LoggerFactory.getLogger(MybBackExcuteService.class);
	
	@DubboReference
	private DriverService driverService;
	
	@DubboReference
	private DriverAuditService driverAuditService;
	
	@DubboReference
	private DriverCarService driverCarService;
	
	@DubboReference
	private DriverBankService driverBankService;
	
	@DubboReference
    private MybService mybService;
	
	@DubboReference
    private MsService msService;

	@DubboReference
	private TransportOrderService transportOrderService;

	@DubboReference
	private TransportOrderExtService transportOrderExtService;

	@DubboReference
	private AppointService appointService;

	@DubboReference
	private AppointExtraService appointExtraService;

	@DubboReference
	private LogisticsService logisticsService;

	@DubboReference
	private TransportOrderBankService transportOrderBankService;

	@DubboReference
	private SmsCodeService smsCodeService;

	@DubboReference
	private WxPayService wxPayService;

	@DubboReference
	private StatementTransportDataService statementTransportDataService;

    public Boolean excuteMybData(String data) {
		try {
			Map<String, Object> g7Map = JsonUtil.fromJson(data, Map.class);
			String event = ObjectUtil.valueOfString(g7Map.get("event"));

			LOGGER.info("【Myb回调参数-->event:{}】-->参数：{}", event, data);
			switch (event) {
				case MybConstant.DRIVER_CHECK_RESULT: 		//司机审核结果
					List driverList = JsonUtil.fromJson(g7Map.get("content").toString(), List.class);
					if(CollectionUtil.isNotEmpty(driverList)) {
						this.processDriverAudit(driverList);
					}
					break;
	
				case MybConstant.CAR_CHECK_RESULT:  //车辆审核结果
					List carList = JsonUtil.fromJson(g7Map.get("content").toString(), List.class);
					if(CollectionUtil.isNotEmpty(carList)) {
						this.processCarAudit(carList);
					}
					break;
					
				case MybConstant.PAYEE_CHECK_RESULT:  //收款人审核结果
					List bankList = JsonUtil.fromJson(g7Map.get("content").toString(), List.class);
					if(CollectionUtil.isNotEmpty(bankList)) {
						this.processBankAudit(bankList);
					}
					break;

				case CmdConstant.WAYBILL_PAY_RESULT: //运单支付结果推送
					MybPayCallbackVO payVo = JsonUtil.fromJson(data, MybPayCallbackVO.class);
					List<MybPayCallbackVO.Content> content = payVo.getContent();
					if (CollectionUtil.isEmpty(content)) {
						LOGGER.error("煤易宝承运平台运单支付状态回调,异步回调返回,结果为空：{}", data);
						return Constant.IS_TRUE;
					}
					for (MybPayCallbackVO.Content item : content) {
						String no = item.getNo();
						Integer payStatus = item.getPayStatus();
						List<MybPayCallbackVO.Bank> bankPayList = item.getBankList();
						if (StringUtil.isEmpty(no)) {
							LOGGER.error("煤易宝承运平台运单支付状态回调,异步回调返回,运单号为空：{}", data);
							continue;
						}
						if (payStatus == null) {
							LOGGER.error("煤易宝承运平台运单支付状态回调,异步回调返回,支付状态为空：{}", data);
							continue;
						}
						TransportOrder cto = transportOrderService.selectByNo(no);
						if (cto == null) {
							LOGGER.error("煤易宝承运平台运单支付状态回调,异步回调返回，运单不存在：{}", data);
							continue;
						}
						//运单支付状态
						switch (payStatus) {
							case 0 ://支付失败
								LOGGER.warn("煤易宝承运平台运单支付状态回调,异步回调返回，支付失败：{}", data);
								break;
							case 1 ://支付中
								LOGGER.warn("煤易宝承运平台运单支付状态回调,异步回调返回，支付中：{}", data);
								break;
							case 2://支付完成
								TransportOrder ctoPayUpd = new TransportOrder();
								ctoPayUpd.setId(cto.getId());
								ctoPayUpd.setStatus(TransportStatusEnum.PAY.getCode());
								ctoPayUpd.setMerchantDriverPaymentTime(new Date()); // 打款时间
								transportOrderService.updateByPrimaryKeySelective(ctoPayUpd);
								sendMsg(cto);
								//资金管理2：司机被欠运费平账记录，司机运费流水
								driverOwedFreightPaid(cto);
								break;
							case 3 ://部分支付
								LOGGER.warn("煤易宝承运平台运单支付状态回调,异步回调返回，部分支付：{}", data);
								break;
							default:
								LOGGER.error("煤易宝承运平台运单支付状态回调,异步回调返回，payStatus格式有误：{}", data);
						}
						//银行卡状态
						if (CollectionUtil.isNotEmpty(bankPayList)) {
							for (MybPayCallbackVO.Bank bank : bankPayList) {
								String id = bank.getId();//银行卡号
								String error = bank.getError();
								BigDecimal payCost = bank.getPayCost();
								Integer payStatusBank = bank.getPayStatus();
								if (id == null) {
									LOGGER.error("煤易宝承运平台运单支付状态回调,异步回调返回，银行卡ID为空：{}", data);
									continue;
								}
								if (payStatusBank == null) {
									LOGGER.error("煤易宝承运平台运单支付状态回调,异步回调返回，银行卡支付状态为空：{}", data);
									continue;
								}
								//银行卡支付状态
								TransportOrderBank tobParam = new TransportOrderBank();
								tobParam.setFkTransportId(cto.getId());
								tobParam.setBankAccount(id);
								List<TransportOrderBank> tobs = transportOrderBankService.selectList(tobParam);
								if (CollectionUtil.isEmpty(tobs)) {
									LOGGER.warn("煤易宝承运平台运单支付状态回调,异步回调返回，银行卡信息不存在：{}", data);
									continue;
								}
								TransportOrderBank tob = tobs.get(0);

								TransportOrderBank ctbUpd = new TransportOrderBank();
								ctbUpd.setId(tob.getId());
								ctbUpd.setUpdateTime(new Date());
								switch (payStatusBank) {
									case 0 ://未支付
										LOGGER.warn("煤易宝承运平台运单支付状态回调,异步回调返回，银行卡未支付：{}", data);
										break;
									case 1 ://支付中
										ctbUpd.setPayStatus(2);
										ctbUpd.setPayTime(new Date());
										transportOrderBankService.updateByPrimaryKeySelective(ctbUpd);
										break;
									case 2://支付完成
										ctbUpd.setPayStatus(1);
										ctbUpd.setPayTime(new Date());
										transportOrderBankService.updateByPrimaryKeySelective(ctbUpd);
										break;
									case 3 ://支付失败
										ctbUpd.setPayStatus(3);
										ctbUpd.setPayTime(new Date());
										transportOrderBankService.updateByPrimaryKeySelective(ctbUpd);

										if (StringUtil.isNotEmpty(error)) {
											TransportOrderExt updateError = new TransportOrderExt();
											updateError.setId(cto.getId());
											updateError.setLogisticsError(error);
											transportOrderExtService.updateByPrimaryKeySelective(updateError);
										}
										break;
									default:
										LOGGER.error("煤易宝承运平台运单支付状态回调,异步回调返回，payStatus格式有误：{}", data);
								}
							}
						}
					}
					break;

				case  CmdConstant.WAYBILL_INVOICE_RESULT: //开票结果推送
					CmdInvoiceCallbackVo invoiceVo = JsonUtil.fromJson(data, CmdInvoiceCallbackVo.class);
					List<CmdInvoiceCallbackVo.Content> invoiceContent = invoiceVo.getContent();
					if (CollectionUtil.isEmpty(invoiceContent)) {
						LOGGER.error("煤易宝承运平台运单开票结果变更推送,异步回调返回,结果为空：{}", data);
						return Constant.IS_TRUE;
					}
					for (CmdInvoiceCallbackVo.Content item : invoiceContent) {
						String no = item.getNo();
						Integer invoiceStatus = item.getInvoiceStatus();//开票状态 0未开票1已开票2已作废
						BigDecimal invoiceAmount = item.getInvoiceAmount();//开票金额,单位：元
						TransportOrder cto = transportOrderService.selectByNo(no);
						if (cto == null) {
							LOGGER.error("煤易宝承运平台运单开票状态回调,异步回调返回，运单不存在：{}", data);
							continue;
						}
						if (invoiceStatus == null) {
							LOGGER.error("煤易宝承运平台运单开票状态回调,异步回调返回，开票状态为空：{}", data);
							continue;
						}
						if (invoiceAmount == null) {
							LOGGER.error("煤易宝承运平台运单开票状态回调,异步回调返回，开票金额为空：{}", data);
							continue;
						}
						switch (invoiceStatus) {
							case 0 ://未开票
								LOGGER.warn("煤易宝承运平台运单开票状态回调,异步回调返回，运单未开票：{}", data);
								break;
							case 1://已开票
								TransportOrder ctoInvoiceAmountUpd = new TransportOrder();
								ctoInvoiceAmountUpd.setId(cto.getId());
								ctoInvoiceAmountUpd.setLogisticsMerchantInvoiceAmount(invoiceAmount);
								ctoInvoiceAmountUpd.setLogisticsMerchantInvoiceStatus(1);
								transportOrderService.updateByPrimaryKeySelective(ctoInvoiceAmountUpd);

								statementTransportDataService.transportCompanyInvoiceNotify(cto.getNo(), invoiceAmount);
								break;
							case 2 ://已作废
								TransportOrder invoiceCancel = new TransportOrder();
								invoiceCancel.setId(cto.getId());
								invoiceCancel.setLogisticsMerchantInvoiceStatus(2);
								transportOrderService.updateByPrimaryKeySelective(invoiceCancel);
								break;
							default:
								LOGGER.error("煤易宝承运平台运单开票状态回调,异步回调返回，payStatus格式有误：{}", data);
						}
					}
					break;

				case  CmdConstant.WAYBILL_CHECK_RESULT: //运单审核结果推送
					MybCheckCallbackVo checkVo = JsonUtil.fromJson(data, MybCheckCallbackVo.class);
					List<MybCheckCallbackVo.Content> checkContent = checkVo.getContent();
					if (CollectionUtil.isEmpty(checkContent)) {
						LOGGER.error("煤易宝承运平台运单审核变更推送,异步回调返回,结果为空：{}", data);
						return Constant.IS_TRUE;
					}
					for (MybCheckCallbackVo.Content item : checkContent) {
						String no = item.getNo();
						Integer checkStatus = item.getCheckStatus();//运单审核状态 0审核未通过1审核通过
						TransportOrder cto = transportOrderService.selectByNo(no);
						if (cto == null) {
							LOGGER.error("煤易宝承运平台运单审核状态回调,异步回调返回，运单不存在：{}", data);
							continue;
						}
						if (checkStatus == null) {
							LOGGER.error("煤易宝承运平台运单审核状态回调,异步回调返回，审核状态为空：{}", data);
							continue;
						}
						switch (checkStatus) {
							case 0 ://审核未通过
								LOGGER.warn("煤易宝承运平台运单审核状态回调,异步回调返回，运单未通过：{}", data);
								break;
							case 1://审核通过
								TransportOrderExt ctrCheckUpd = new TransportOrderExt();
								ctrCheckUpd.setId(cto.getId());
								ctrCheckUpd.setLogisticsCheckStatus(1);
								transportOrderExtService.updateByPrimaryKeySelective(ctrCheckUpd);

								LogisticsSignPO waybill = new LogisticsSignPO();
								waybill.setOrderNumber(cto.getNo());
								msService.send(MsEnum.TRANSPORT_SIGN, JsonUtil.toJson(waybill));
								break;
							default:
								LOGGER.error("煤易宝承运平台运单审核状态回调,异步回调返回，checkStatus格式有误：{}", data);
						}
					}
					break;

				default:
					break;
			}
			return Constant.IS_TRUE;
		} catch (RuntimeException e) {
            LOGGER.warn("处理Myb回调业务异常,{}", data, e);
            return Constant.IS_FALSE;
		} catch (Exception e) {
            LOGGER.error("处理Myb回调业务异常,{}", data, e);
            return Constant.IS_FALSE;
		}
	}
    
    /**
     * 司机信息认证处理
     * @title processDriverAudit
     * @param driverList void
     * @author wangqinghua 
     * @throws InterruptedException 
     * @date 2023年3月21日 下午4:29:12
     */
    private void processDriverAudit(List driverList) throws InterruptedException {
    	Thread.sleep(1500);
		for (Object object : driverList) {
			Map contentMap = JSONObject.parseObject(object.toString(), Map.class);
			if(MapUtil.isEmpty(contentMap)) {
				continue;
			}
			
			String driverCard = ObjectUtil.valueOfString(contentMap.get("driverCard"));
			String driverMobile = ObjectUtil.valueOfString(contentMap.get("driverPhone"));
			Integer checkStatus = ObjectUtil.valueOfInteger(contentMap.get("checkStatus"));
			
			Driver driver = driverService.selectByMobile(driverMobile);
			if(driver == null) {
				continue;
			}
			
			DriverAudit tempDriverAudit = driverAuditService.selectRelation(driver.getId(), driverCard, ChannelTypeEnum.MYB.getKey());
			if(tempDriverAudit == null) {
				continue;
			}
			
			DriverAudit paramDriverAudit = new DriverAudit();
			paramDriverAudit.setId(tempDriverAudit.getId());
			paramDriverAudit.setAuditType(Constant.IS1);
			paramDriverAudit.setChannelType(ChannelTypeEnum.MYB.getKey());
			paramDriverAudit.setUpdator(ChannelTypeEnum.MYB.getName());
			paramDriverAudit.setUpdateTime(new Date());
			if(EqualsUtil.isEquals(checkStatus, Constant.IS0)) {
				continue;
			}else if(EqualsUtil.isEquals(checkStatus, Constant.IS1)){
				paramDriverAudit.setAuditStatus(Constant.IS1);
			}else if(EqualsUtil.isEquals(checkStatus, Constant.IS2)){
				paramDriverAudit.setAuditStatus(Constant.IS3);
				String errorMsg = ObjectUtil.valueOfString(contentMap.get("errorMsg"));
				paramDriverAudit.setRemark(errorMsg);
			}
			driverAuditService.updateAuditStatus(paramDriverAudit);
		}
    }
    
    /**
     * 车辆认证信息处理
     * @title processCarAudit
     * @param carList void
     * @author wangqinghua 
     * @throws InterruptedException 
     * @date 2023年3月21日 下午4:29:18
     */
    private void processCarAudit(List carList) throws InterruptedException {
    	Thread.sleep(1500);
    	for (Object object : carList) {
			Map contentMap = JSONObject.parseObject(object.toString(), Map.class);
			if(MapUtil.isEmpty(contentMap)) {
				continue;
			}
			
			String licenseNumber = ObjectUtil.valueOfString(contentMap.get("licenseNumber"));
			if(StringUtil.isEmpty(licenseNumber)) {
				continue;
			}
			
			Integer checkStatus = ObjectUtil.valueOfInteger(contentMap.get("checkStatus"));
			String error = ObjectUtil.valueOfString(contentMap.get("error"));
			if(EqualsUtil.isEquals(checkStatus, Constant.IS0)) {
				continue;
			}else if(EqualsUtil.isEquals(checkStatus, Constant.IS1)) {
				checkStatus = Constant.IS1;
			}else if(EqualsUtil.isEquals(checkStatus, Constant.IS2)) {
				checkStatus = Constant.IS3;
			}
			
			DriverCar paramDriverCar = new DriverCar();
			paramDriverCar.setPlateNumber(licenseNumber);
			paramDriverCar.setChannelType(ChannelTypeEnum.MYB.getKey());
			paramDriverCar.setStatus(Constant.IS1);
			paramDriverCar.setAuditStatus(AuditStatusEnum.AUTHING.getKey());
			List<DriverCar> driverCarList = driverCarService.selectList(paramDriverCar);
			if(CollectionUtil.isEmpty(driverCarList)) {
				continue;
			}
			
			for (DriverCar driverCar : driverCarList) {
				DriverCar updateDriverCar = new DriverCar();
				updateDriverCar.setId(driverCar.getId());
				updateDriverCar.setAuditStatus(checkStatus);
				updateDriverCar.setRemark(error);
				updateDriverCar.setAuditType(Constant.IS1);
				updateDriverCar.setUpdator(ChannelTypeEnum.MYB.getName());
				updateDriverCar.setUpdateTime(new Date());
				driverCarService.updateAuditStatus(updateDriverCar);
			}
		}
    }
    
    /**
     * 收款人处理
     * @title processBankAudit
     * @param bankList
     * @throws ServiceException void
     * @author wangqinghua 
     * @throws InterruptedException 
     * @date 2023年3月21日 下午4:29:23
     */
    private void processBankAudit(List bankList) throws ServiceException, InterruptedException {
    	Thread.sleep(1500);
    	for (Object object : bankList) {
			Map contentMap = JSONObject.parseObject(object.toString(), Map.class);
			if(MapUtil.isEmpty(contentMap)) {
				continue;
			}
			
			String payeeCard = ObjectUtil.valueOfString(contentMap.get("payeeCard"));
			String payeeName = ObjectUtil.valueOfString(contentMap.get("payeeName"));
			String payeeMobile = ObjectUtil.valueOfString(contentMap.get("payeeMobile"));
			String bankCardNumber = ObjectUtil.valueOfString(contentMap.get("bankCardNumber"));
			Integer checkStatus = ObjectUtil.valueOfInteger(contentMap.get("checkStatus"));
			String errorMsg = ObjectUtil.valueOfString(contentMap.get("errorMsg"));
			if(EqualsUtil.isEquals(checkStatus, Constant.IS0)) {
				continue;
			}else if(EqualsUtil.isEquals(checkStatus, Constant.IS1)) {
				checkStatus = Constant.IS1;
			}else if(EqualsUtil.isEquals(checkStatus, Constant.IS2)) {
				checkStatus = Constant.IS3;
			}
			
			DriverBank paramDriverBank = new DriverBank();
			paramDriverBank.setOpenName(payeeName);
			paramDriverBank.setOpenMobile(payeeMobile);
			paramDriverBank.setOpenIdcardCode(payeeCard);
			paramDriverBank.setBankAccount(bankCardNumber);
			paramDriverBank.setChannelType(ChannelTypeEnum.MYB.getKey());
			paramDriverBank.setAuditStatus(Constant.IS2);
			paramDriverBank.setStatus(Constant.IS1);
			List<DriverBank> driverBankList = driverBankService.selectList(paramDriverBank);
			if(CollectionUtil.isNotEmpty(driverBankList)) {
				for (DriverBank driverBank : driverBankList) {
					//不用源对象, 防止因并发更改了其它状态信息
					DriverBank updateDriverBank = new DriverBank();
					updateDriverBank.setId(driverBank.getId());
					updateDriverBank.setAuditStatus(checkStatus);
					updateDriverBank.setRemark(errorMsg);
					updateDriverBank.setUpdator(ChannelTypeEnum.MYB.getName());
					updateDriverBank.setUpdateTime(new Date());
					driverBankService.updateByPrimaryKeySelective(updateDriverBank);
				}
			}
		}
    }

	/**
	 * 支付成功消息
	 * @author lijie
	 */
	private void sendMsg(TransportOrder cto) {
		try {
			//第一收款人
			TransportOrderBank bank = getFirstPayee(cto);
			Date inTime = cto.getLoadTime();
			String inTimeStr = DateUtil.date2String(inTime, "yyyy年MM月dd日");
			String msg = "运费已支付：%s运单  %s-%s  运费%s元已支付，请注意查收，感谢使用煤博事。";
			msg = String.format(msg, inTimeStr,
					cto.getSendAddressName(), cto.getReceiveAddressName(), bank.getAmount().toPlainString());
			smsCodeService.sendSmsNotice(cto.getDriverMobile(), msg, false);
			sendMsgWx(cto, bank);
		} catch (Exception e) {
			LOGGER.error("发送消息异常", e);
		}
	}

	/**
	 * 微信小程序消息
	 * @author lijie
	 * @date 2023年3月18日16:02:58
	 */
	private void sendMsgWx(TransportOrder cto, TransportOrderBank bank) {
		Driver tempDriver = driverService.selectByMobile(cto.getDriverMobile());
		if (tempDriver == null || StringUtil.isEmpty(tempDriver.getWxOpenId())) {
			return;
		}
		String templateId = "LF4CUUj95H0g260GdF36VRjwa6k4FpKbCByIAy2TKPE";
		String page = "pages/pickup/index?status=3";
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("amount1", "￥"+bank.getAmount().setScale(2, RoundingMode.HALF_UP) + "元");
		paramMap.put("character_string3", cto.getNo());
		paramMap.put("thing4", cto.getSendAddressName() + "" + cto.getReceiveAddressName());
		paramMap.put("name5", cto.getCustomerName());
		paramMap.put("date6", DateUtil.date2String(bank.getPayTime(),DateUtil.PATTERN_STANDARD));
		try {
			wxPayService.subscribeSend(tempDriver.getWxOpenId(), templateId, page, paramMap);
		} catch (Exception e) {
			LOGGER.warn("发送消息异常", e);
		}
	}

	private TransportOrderBank getFirstPayee(TransportOrder cto) throws Exception {
		AppointExtra ext = appointExtraService.selectByPrimaryKey(cto.getFkAppointId());
		if (ext == null) {
			LOGGER.warn("getFirstPayee error{}", cto.getId());
		}
		Long fkBankId = ext.getBankId();

		TransportOrderBank param = new TransportOrderBank();
		param.setFkTransportId(cto.getId());
		param.setFkStoreBankId(fkBankId);
		List<TransportOrderBank> banks = transportOrderBankService.selectList(param);
		if (CollectionUtil.isEmpty(banks)) {
			throw new Exception(String.format("运单%s未查到银行卡", cto.getNo()));
		}
		if (banks.size()>1) {
			LOGGER.error("运单{}查到两张主银行卡", cto.getNo());
		}
		return banks.get(0);
	}

	private void driverOwedFreightPaid(TransportOrder cto) {
		Appoint ceo = appointService.selectByPrimaryKey(cto.getFkAppointId());
		AppointExtra ceoExt = appointExtraService.selectByPrimaryKey(cto.getFkAppointId());
		PayMentOrderPO pay = new PayMentOrderPO();
		pay.setOrderNo(ceo.getOrderNo());
		pay.setBusinessNo(ceo.getTransportNo());
		pay.setPayerId(cto.getBizMerchantId());
		pay.setPayeeId(cto.getFkDriverId());
		pay.setAmount(cto.getMerchantDriverSettlementAmount());
		pay.setTransportNo(ceo.getTransportNo());
		pay.setBizType(LogisticsBizTypeEnum.driver_real_feight_fee);
		ExtContentPO ext = new ExtContentPO();
		ext.setDriverId(ceo.getDriverAuditId());//司机id
		ext.setDriverAuditName(ceo.getDriverName()); //司机姓名
		ext.setPlateNumber(ceo.getPlateNumber()); //车牌号
		if(StringUtil.isNotBlank(cto.getOpenName())){
			ext.setDriverBankOpenName(cto.getOpenName());
			ext.setBankNumber(cto.getBankAccount());//银行卡号
		}else{
			ext.setDriverBankOpenName(ceoExt.getOpenName());
			ext.setBankNumber(ceoExt.getBankAccount());//银行卡号
		}
		pay.setExtContent(JsonUtil.toJson(ext));
		pay.setSummary("运单支付司机运费,报号单号:"+ceo.getSn());
		pay.setUpdator(cto.getRealReceiveStaffName());
		pay.setUpdateId(cto.getRealReceiveStaffId());
		pay.setOrderNo(cto.getOrderNo());
		msService.send(MsEnum.PAY_DRIVERFEE_HANDLE, JsonUtil.toJson(pay));
	}

}
